package com.elitesland.security;

import com.elitesland.system.entity.SysRoleDO;
import com.elitesland.system.repo.SysPermissionRepo;
import com.elitesland.system.repo.SysRoleRepo;
import lombok.val;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;

import javax.annotation.Resource;
import java.util.Collection;

/**
 * <pre>
 * 动态鉴权的核心，根据访问的URL，获取对应的角色列表
 * </pre>
 *
 * @author Mir
 * @date 2020/6/15
 */
public class DynamicFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Resource
    private RequestMatcherCreator requestMatcherCreator;

    @Resource
    private SysPermissionRepo sysPermissionRepo;

    @Resource
    private SysRoleRepo sysRoleRepo;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        return SecurityConfig.createList();
//
//        val request = ((FilterInvocation) object).getRequest();
//
//        val permissions = sysPermissionRepo.findAll();
//        val metaResources = permissions.stream()
//                .map(p -> Tuples.of(p.getPattern(), p.getHttpMethod()))
//                .collect(Collectors.toSet());
//        val requestMatchers = requestMatcherCreator.convertToRequestMatcher(metaResources);
//
//        val reqMatcher = requestMatchers.stream().filter(m -> m.matches(request))
//                .findAny();
//        if (reqMatcher.isPresent()) {
//            val antPathRequestMatcher = (AntPathRequestMatcher) reqMatcher.get();
//
//            val pattern = antPathRequestMatcher.getPattern();
//            val permRoleCodes = permissions.stream().filter(p -> p.getPattern().equals(pattern))
//                    .flatMap(p -> p.getRoles().stream().map(SysRoleDO::getCode))
//                    .toArray(String[]::new);
//            return SecurityConfig.createList(permRoleCodes);
//        }
//
//        return SecurityConfig.createList();
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        val roleList = sysRoleRepo.findAll();
        val roleCodeList = roleList.stream().map(SysRoleDO::getCode).toArray(String[]::new);
        return SecurityConfig.createList(roleCodeList);
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}
